<template>
  <Designer ref="ddesigner">
    <template v-slot:header>
      <div class="design-name">{{ state.name }}</div>
      <Dialoger v-model="isShowRelease" :onConfirm="handleSubmitRelease" :dialogCls="'d-paner-sm'" title="发布">
        <template v-slot:body>
          <FormGroup label="版本标题" :col="12">
            <FormInput v-model="releaseName" />
          </FormGroup>
          <FormGroup label="版本描述" :col="12">
            <FormTextarea v-model="releaseDesc" />
          </FormGroup>
        </template>
      </Dialoger>
      <Dialoger v-model="isShowReleaseList" :onConfirm="handleCloseRelease" :dialogCls="'d-paner-md'" title="发布版本">
        <template v-slot:body>
          <Grid v-model="releaseList" :isPagerAble="false">
            <GridColumn :width="60" type="index" label="序号" />
            <GridColumn field="name" label="版本号" width="180">
              <template v-slot:body="scope">
                {{ scope.releaseVersion }}
              </template>
            </GridColumn>
            <GridColumn field="name" label="版本名称" width="160">
              <template v-slot:body="scope">
                {{ scope.releaseName }}
              </template>
            </GridColumn>
            <GridColumn field="description" label="描述" />
            <!-- <GridColumn field="updateUser" label="修改人" /> -->
            <GridColumn field="createTime" label="发布时间" format="datetime|yyyy-MM-dd HH:mm:ss" width="160" />
            <!-- <GridColumn field="createUser" label="创建人" /> -->
            <GridColumn field="action" :width="100" label="操作">
              <template v-slot:body="scope">
                <div class="d-bar-tools d-bar-tools-condensed d-grid-actions">
                  <a @click="handleShowReleaseItem(scope)" title="查看" class="d-tools-item d-text-theme"><SeeIcon /></a>
                  <a @click="handleDelReleaseItem(scope)" title="删除" class="d-tools-item d-text-theme"><DeleteIcon /></a>
                </div>
              </template>
            </GridColumn>
          </Grid>
        </template>
      </Dialoger>
    </template>
    <template v-slot:actions-before>
      <el-button @click="handleSubmit" type='primary' size="mini">保存</el-button>
        <el-dropdown split-button type="primary" @click="handleRelease" size="mini">
          发布
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleShowReleaseList">查看版本</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button @click="handlePreview" type='primary' size="mini">预览</el-button>
        <el-button @click="handleBack" size="mini">返回列表</el-button>
    </template>
  </Designer>
</template>

<script>
import Designer from './designer.vue'
import { objecter, parser, dater, strer } from '@daelui/dogjs/dist/components.js'
import { Dialoger, FormGroup, FormInput, FormTextarea, Grid, GridColumn } from '@daelui/vdog/dist/components.js'
import { SeeIcon, DeleteIcon } from '@daelui/vdog/dist/icons.js'
import { zh as locale } from '@daelui/dogjs/dist/locale.js'
import stock, { state, setter } from '@/service/stock/index'
import pageSer from '../../../service/action/viewpage.action'
import vcSer from '@/service/action/viewcomp.action'
import vrSer from '@/service/action/viewrelease.action'
import componentCollection from './components/components'

export default {
  components: {
    Designer,
    Dialoger,
    FormGroup, FormInput, FormTextarea,
    Grid, GridColumn,
    SeeIcon, DeleteIcon
  },

  data () {
    return {
      isEdit: false, // 是否是编辑模式
      stock,
      // 表单数据
      state: {
        id: '',
        pid: '',
        name: '',
        meta: {},
        layout: '',
        description: '',
        status: 1,
        order: 1,
        updateTime: '',
        updateUser: '',
        createTime: '',
        createUser: ''
      },
      isShowRelease: false, // 是否显示发布框
      releaseName: '',
      releaseDesc: '', // 发布描述
      isShowReleaseList: false,
      releaseList: [] // 发布版本列表
    }
  },

  methods: {
    // 初始化
    init () {
      // this.registryWidget()
      this.stock.setter.setComponentCollection(componentCollection)
    },
    async registryWidget () {
      let widgets = {
        registry: 'http://www.daelui.cn/pool/prod/widgets.json',
        rootUrl: 'http://www.daelui.cn/pool/prod/widgets'
      }
      let res = await fetch(widgets.registry)
      let data = await res.json()
      data.forEach(item => {
        let rootUrl = widgets.rootUrl
        item.main = item.main.replace('{rootUrl}', rootUrl)
        item.property = item.property.replace('{rootUrl}', rootUrl)
        if (item.repository) {
          item.repository.main = item.repository.main.replace('{rootUrl}', rootUrl)
          item.repository.property = item.repository.property.replace('{rootUrl}', rootUrl)
        }
      })
      this.stock.setter.setComponentCollection(data)
    },
    /**
     * @function 加载数据
    */
    loadItem (id) {
      pageSer.queryItem({ id }).then(result => {
        let data = result.data || {}
        // 组件元数据
        let meta = parser.parse(data.meta) || {
          component: 'div',
          name: data.layout || '',
          properts: {},
          layout: {},
          events: {},
          resource: {},
          theme: {},
          childComponents: []
        }
        meta.childComponents = meta.childComponents || []
        data.meta = meta
        this.state = data
        state.page = data
        // 设置页面title
        if (data.name) {
          document.title = data.name
        }
      })
      // 查询版本
      this.loadReleaseList(id)
    },

    // 加载版本列表
    loadReleaseList (id) {
      // 查询版本
      vrSer.queryListAll({vpid: id || '-9999'}).then(res => {
        let data = res.data
        data = Array.isArray(data) ? data : []
        this.releaseList = data
      })
    },

    /**
     * @function 提交
    */
    handleSubmit ({ isShowMessage }) {
      let defer = null
      let state = objecter.clone(this.state)
      // 页面元数据
      state.meta = this.getMetaValue()
      state.meta = parser.stringify(state.meta)
      state = {
        id: state.id,
        meta: state.meta
      }
      // 编辑
      if (this.isEdit) {
        defer = pageSer.editItem(state)
      } else { // 添加
        defer = pageSer.addItem(state)
      }
      return defer.then(result => {
        if (isShowMessage !== false) {
          if (result.success) {
            this.$message({
              message: locale.action.success,
              type: 'success',
              showClose: true
            })
            // 添加则回到列表页
            if (!this.isEdit) {
              this.$router.push(this.getMicroRoute('/dview/page/list'))
            }
          } else {
            this.$message({
              message: locale.action.fail,
              type: 'error',
              showClose: true
            })
          }
        }
        return result
      })
    },

    // 发布
    handleRelease () {
      if (!this.state.id) {
        this.$message({
          message: '需要先保存后再进行发布',
          type: 'warning',
          showClose: true
        })
        return false
      }
      this.releaseDesc = ''
      this.releaseName = dater.format(new Date(), 'yyyy-MM-dd HH:mm:ss'),
      this.isShowRelease = true
    },

    // 发送发布
    handleSubmitRelease () {
      // 先保存
      this.handleSubmit({ isShowMessage: false }).then((result) => {
        if (result.success) {
          let state = objecter.clone(this.state)
          // 页面元数据
          state.meta = this.getMetaValue()
          state.meta = parser.stringify(state.meta)
          vrSer.addItem({
            vpid: state.id,
            releaseName: this.releaseName,
            description: this.releaseDesc,
            releaseVersion: dater.format(new Date(), 'yyyyMMddHHmmss') + strer.urid(4, false, true),
            name: state.name,
            path: state.path,
            code: state.code,
            layout: state.layout,
            meta: state.meta,
            mid: state.mid,
            status: state.status,
            labels: state.labels
          }).then(result => {
            if (result.success) {
              this.$message({
                message: '发布成功',
                type: 'success',
                showClose: true
              })
              // 查询版本
              this.loadReleaseList(this.state.id)
            } else {
              this.$message({
                message: '发布失败',
                type: 'error',
                showClose: true
              })
            }
          })
        } else {
          this.$message({
            message: locale.action.fail,
            type: 'error',
            showClose: true
          })
        }
      })
    },

    // 显示版本列表
    handleShowReleaseList () {
      this.isShowReleaseList = true
    },
    // 关闭版本列表
    handleCloseRelease () {
      this.isShowReleaseList = false
    },
    // 版本详细
    handleShowReleaseItem (item) {
      // 组件元数据
      let meta = parser.parse(item.meta)
      meta.childComponents = meta.childComponents || []
      this.state.meta = meta
      state.page.meta = meta
      this.isShowReleaseList = false
    },
    // 删除版本
    handleDelReleaseItem (item) {
      Dialoger.confirm(locale.message.confirmDelete).then(b => {
        if (!b) {
          return false
        }
        vrSer.removeItem({ id: item.id}).then((res) => {
          if (res.success) {
            this.$message({
              message: locale.action.success,
              type: 'success',
              showClose: true
            })
          } else {
            this.$message({
              message: locale.action.fail,
              type: 'error',
              showClose: true
            })
          }
          // 查询版本
          this.loadReleaseList(this.state.id)
        })
      })
    },

    // 预览
    handlePreview () {
      if (!this.state.id) {
        this.$message({
          message: '需要先保存后再进行预览',
          type: 'warning',
          showClose: true
        })
        return false
      }
      window.open(this.getMicroPath('#/dview/page/view/' + this.state.id))
    },

    /**
     * @function 获取元数据
    */
    getMetaValue () {
      return this.$refs.ddesigner.getMetaValue()
    },

    /**
     * @function 返回
    */
    handleBack () {
      this.$router.push(this.getMicroRoute('/dview/page/list'))
    }
  },

  created () {
    // 查询所有视图组件
    vcSer.queryAllComponents().then(cps => {
      setter.setComponentCollection(cps)
    })
    // 初始化
    this.init()
  },

  mounted () {
    let params = this.$route.params
    // 新建
    if (!params.id) {
      this.isEdit = false
    } else { // 编辑
      this.isEdit = true
      this.loadItem(params.id)
    }

    // 快捷保存
    this.handleSave = (event) => {
      if (event.ctrlKey && event.key === 's') {
        event.preventDefault()
        this.handleSubmit({})
        return false
      }
    }

    // 拦截CTRL+S事件
    document.addEventListener('keydown', this.handleSave)
  },

  beforeDestroy () {
    // 解除CTRL+S事件
    document.removeEventListener('keydown', this.handleSave)
  }
}
</script>

<style lang="less" scoped>

</style>

<style lang="less">

</style>
